<?php

$mysqli = new mysqli("localhost", "root", "zjzdw7980", "mydesktop");
$has_db = false;

if (!$mysqli->connect_errno)
{
    if (!$mysqli->query(
        'CREATE TABLE IF NOT EXISTS words (name VARCHAR(64) NOT NULL,
                                           priority INT NOT NULL DEFAULT 0,
                                           date DATE NOT NULL,
                                           notes VARCHAR(256),
                                           PRIMARY KEY (name))'))
    {
        echo "Table creation failed: (" . $mysqli->errno . ") ". $mysqli->error;
    }
    else
    {
        $has_db = true;
    }
}

if ($has_db)
{
    if ($_POST["word"] == null) 
    {
        $sql = "SELECT * FROM words ORDER BY RAND() LIMIT 1";
        $res = $mysqli->query($sql);
        if ($res->num_rows>0)
        {
            $output[]=$res->fetch_assoc();
            print(json_encode($output));
        }
    }
    else 
    {
        $sql = "INSERT INTO words VALUES('".$_POST["word"]."',0,CURDATE(),'')";
        echo $sql;
        if (!$mysqli->query($sql))
        {
          echo "Table insertion failed: (" . $mysqli->errno . ") ". $mysqli->error;
         }
    }
}

$mysqli->close();
?>

